package com.gitee.melin.bee.util;

import static java.util.regex.Pattern.CASE_INSENSITIVE;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;

public class PasswordMaskerUtils {

    private static final String PASSWORD_MASK = "******";

    private static final String PASSWORD_CONTAINING_REGEX =
            "(.*)(password|secretAccessKey|secretKey)[\\'\\\"]?[\\s]*[=:][\\s]*[\\'\\\"]?(.*)[\\'\\\"]";

    private static final Pattern PASSWORD_CONTAINING_PATTERN =
            Pattern.compile(PASSWORD_CONTAINING_REGEX, CASE_INSENSITIVE);

    public static String mask(String value) {
        if (value == null || value.isEmpty()) {
            return value;
        }

        return maskPasswordFragments(value);
    }

    private static String maskPasswordFragments(String value) {
        StringBuilder maskedBuilder = new StringBuilder();
        Matcher matcher = PASSWORD_CONTAINING_PATTERN.matcher(value);

        int start = 0, end;
        while (matcher.find()) {
            end = matcher.start();

            maskedBuilder.append(value.substring(start, end));

            String group = matcher.group(0);
            String password = matcher.group(3);
            group = StringUtils.replace(group, password, PASSWORD_MASK);
            maskedBuilder.append(group);

            start = matcher.end();
        }

        maskedBuilder.append(value.substring(start));

        if (maskedBuilder.length() == 0) {
            return value;
        }
        return maskedBuilder.toString();
    }
}
